import { Model, DataTypes, Op } from 'sequelize';
import db from '../db/mysql';

class MusenumUserTimes extends Model {
  id: number;
  userid: string;
  token: string;
  phonenumber: string;
  date: string;
  times: number;
  platform: number;
}

MusenumUserTimes.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    userid: {
      type: DataTypes.STRING(100),
      defaultValue: '',
      comment: '时间',
    },
    platform: {
      type: DataTypes.TINYINT({ length: 1 }),
      defaultValue: 1,
      comment: '平台',
    },
    date: {
      type: DataTypes.STRING(100),
      defaultValue: '',
      comment: '时间',
    },
    phonenumber: {
      type: DataTypes.STRING(20),
      defaultValue: '',
      comment: '手机号',
    },
    token: {
      type: DataTypes.STRING(500),
      defaultValue: '',
      comment: 'token',
    },
    times: {
      type: DataTypes.TINYINT({ length: 1 }),
      defaultValue: 0,
      comment: '次数',
    },
  },
  {
    sequelize: db,
    freezeTableName: true,
    tableName: 't_musenum_user_times',
    indexes: [
      {
        fields: ['userid'],
      },
      {
        fields: ['userid', 'date'],
      },
    ],
  }
);

//强制初始化数据库
// MusenumUserTimes.sync({ force: true });

export default {
  sync(force = true) {
    return MusenumUserTimes.sync({ force });
  },
  insert: function (model: any) {
    return MusenumUserTimes.create(model);
  },
  update(data, id) {
    return MusenumUserTimes.update(data, { where: { id } });
  },
  findOneByDate(userid, date) {
    return MusenumUserTimes.findOne(
      { 
        where: {
          date,
          userid,
        }, 
        attributes: ['id', 'userid', 'phonenumber', 'token', 'times']
      });
  },
  findOneAvailable(date, times) {
    return MusenumUserTimes.findOne(
      { 
        where: {
          date,
          times: {
            [Op.lte]: times
          }
        }, 
        attributes: ['id', 'userid', 'phonenumber', 'token', 'times']
      });
  }
};
